package com.css.zfzx.sjcj.modules.hddcA1LiteratureDocumentTable.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcA1LiteratureDocumentTable.repository.HddcA1LiteraturedocumenttableNativeRepository;
import com.css.zfzx.sjcj.modules.hddcA1LiteratureDocumentTable.repository.HddcA1LiteraturedocumenttableRepository;
import com.css.zfzx.sjcj.modules.hddcA1LiteratureDocumentTable.repository.entity.HddcA1LiteraturedocumenttableEntity;
import com.css.zfzx.sjcj.modules.hddcA1LiteratureDocumentTable.service.HddcA1LiteraturedocumenttableService;
import com.css.zfzx.sjcj.modules.hddcA1LiteratureDocumentTable.viewobjects.HddcA1LiteraturedocumenttablePageVO;
import com.css.zfzx.sjcj.modules.hddcA1LiteratureDocumentTable.viewobjects.HddcA1LiteraturedocumenttableQueryParams;
import com.css.zfzx.sjcj.modules.hddcA1LiteratureDocumentTable.viewobjects.HddcA1LiteraturedocumenttableVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 区域调查数据-文献资料库-属性表管理
 * @author zyb
 * @date 2020-11-30
 */
@Service
public class HddcA1LiteraturedocumenttableServiceImpl implements HddcA1LiteraturedocumenttableService {

    private final HddcA1LiteraturedocumenttableRepository hddcA1LiteraturedocumenttableRepository;
    private final HddcA1LiteraturedocumenttableNativeRepository hddcA1LiteraturedocumenttableNativeRepository;
    private final LiteratureInformationExcelVerifyHandler literatureInformationExcelVerifyHandler;

    @Autowired
    public HddcA1LiteraturedocumenttableServiceImpl(HddcA1LiteraturedocumenttableRepository hddcA1LiteraturedocumenttableRepository,
                                                    HddcA1LiteraturedocumenttableNativeRepository hddcA1LiteraturedocumenttableNativeRepository,
                                                    LiteratureInformationExcelVerifyHandler literatureInformationExcelVerifyHandler) {
        this.hddcA1LiteraturedocumenttableRepository = hddcA1LiteraturedocumenttableRepository;
        this.hddcA1LiteraturedocumenttableNativeRepository = hddcA1LiteraturedocumenttableNativeRepository;
        this.literatureInformationExcelVerifyHandler = literatureInformationExcelVerifyHandler;
    }

    @Override
    public JSONObject queryHddcA1Literaturedocumenttables(HddcA1LiteraturedocumenttableQueryParams queryParams, int curPage, int pageSize, String sort, String order) {
        Page<HddcA1LiteraturedocumenttablePageVO> hddcA1LiteraturedocumenttablePage = this.hddcA1LiteraturedocumenttableNativeRepository.queryHddcA1Literaturedocumenttables(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcA1LiteraturedocumenttablePage);
    }


    @Override
    public HddcA1LiteraturedocumenttableEntity getHddcA1Literaturedocumenttable(String id) {
        return this.hddcA1LiteraturedocumenttableRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcA1LiteraturedocumenttableEntity saveHddcA1Literaturedocumenttable(HddcA1LiteraturedocumenttableEntity hddcA1Literaturedocumenttable) {
        hddcA1Literaturedocumenttable.setUuid(UUIDGenerator.getUUID());
        hddcA1Literaturedocumenttable.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcA1Literaturedocumenttable.setCreateTime(now);
        hddcA1Literaturedocumenttable.setUpdateTime(now);
        hddcA1Literaturedocumenttable.setIsValid(PlatformConstants.Y);
        hddcA1Literaturedocumenttable.setQualityinspectionStatus(PlatformConstants.N);
        hddcA1Literaturedocumenttable.setExtends10(PlatformConstants.Y);
        this.hddcA1LiteraturedocumenttableRepository.save(hddcA1Literaturedocumenttable);
        return hddcA1Literaturedocumenttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcA1LiteraturedocumenttableEntity updateHddcA1Literaturedocumenttable(HddcA1LiteraturedocumenttableEntity hddcA1Literaturedocumenttable) {
        HddcA1LiteraturedocumenttableEntity entity = hddcA1LiteraturedocumenttableRepository.findById(hddcA1Literaturedocumenttable.getUuid()).get();
        UpdateUtil.copyNullProperties(entity, hddcA1Literaturedocumenttable);
        hddcA1Literaturedocumenttable.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcA1Literaturedocumenttable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcA1LiteraturedocumenttableRepository.save(hddcA1Literaturedocumenttable);
        return hddcA1Literaturedocumenttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcA1Literaturedocumenttables(List<String> ids) {
        List<HddcA1LiteraturedocumenttableEntity> hddcA1LiteraturedocumenttableList = this.hddcA1LiteraturedocumenttableRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(hddcA1LiteraturedocumenttableList) && hddcA1LiteraturedocumenttableList.size() > 0) {
            for (HddcA1LiteraturedocumenttableEntity hddcA1Literaturedocumenttable : hddcA1LiteraturedocumenttableList) {
//                this.hddcA1LiteraturedocumenttableRepository.delete(hddcA1Literaturedocumenttable);
                hddcA1Literaturedocumenttable.setIsValid(PlatformConstants.N);
                hddcA1Literaturedocumenttable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Literaturedocumenttable.setUpdateTime(new Date());
                this.hddcA1LiteraturedocumenttableRepository.save(hddcA1Literaturedocumenttable);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public void exportFile(HddcA1LiteraturedocumenttableQueryParams queryParams, HttpServletResponse response) {
        List<HddcA1LiteraturedocumenttableEntity> yhDisasterEntities = hddcA1LiteraturedocumenttableNativeRepository.exportYhDisasters(queryParams);
        List<HddcA1LiteraturedocumenttableVO> list = new ArrayList<>();
        for (HddcA1LiteraturedocumenttableEntity entity : yhDisasterEntities) {
            HddcA1LiteraturedocumenttableVO yhDisasterVO = new HddcA1LiteraturedocumenttableVO();
            BeanUtils.copyProperties(entity, yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "文献资料库", "文献资料库",
                HddcA1LiteraturedocumenttableVO.class, "文献资料库.xls", response);
    }

    @Override
    public String importExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(literatureInformationExcelVerifyHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcA1LiteraturedocumenttableVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcA1LiteraturedocumenttableVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcA1LiteraturedocumenttableVO yhDisasterVO : result.getFailList()) {
                    returnMsg.append("第").append(yhDisasterVO.getRowNum()).append("行").append(yhDisasterVO.getErrorMsg()).append("<br/>");
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcA1LiteraturedocumenttableVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).toString();
        } catch (Exception e) {
            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcA1LiteraturedocumenttableEntity> hddcA1InvrgnhasmaterialtableList = this.hddcA1LiteraturedocumenttableRepository.queryByProjectId(projectIds);
        if (!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for (HddcA1LiteraturedocumenttableEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid(PlatformConstants.N);
                this.hddcA1LiteraturedocumenttableRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcA1LiteraturedocumenttableEntity> hddcA1InvrgnhasmaterialtableList = this.hddcA1LiteraturedocumenttableRepository.queryByTaskId(taskId);
        if (!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for (HddcA1LiteraturedocumenttableEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid(PlatformConstants.N);
                this.hddcA1LiteraturedocumenttableRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     */
    public void saveDisasterList(List<HddcA1LiteraturedocumenttableVO> list) {
        for (HddcA1LiteraturedocumenttableVO hddcA1LiteraturedocumenttableVO : list) {
            HddcA1LiteraturedocumenttableEntity yhDisasterEntity = new HddcA1LiteraturedocumenttableEntity();
            BeanUtils.copyProperties(hddcA1LiteraturedocumenttableVO, yhDisasterEntity);
            saveHddcA1Literaturedocumenttable(yhDisasterEntity);
        }
    }
}
